<script setup>
import {nextTick, onMounted, ref} from "vue";
import {getCategoryList, removeCategory, saveCategory} from "@/api/category.js";
import {ElMessage} from "element-plus";

const loading = ref(false);
const tableData = ref([]);
// 删除分类
const deleteCategory = async (row) => {
  console.log(row);
  await removeCategory(row?.id).then(res => {
    console.log(res);
    ElMessage.success('删除成功');
    doQuery();
  }).catch(err => {
    console.log(err);
    ElMessage.error('删除失败');
  })
};
const pagination = ref({
  pageSize: 5,
  pageNum: 1
});
const totalArticleCount = ref(0);
const dialog = ref({
  visible: false,
  title: '新增分类'
});
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val;
  doQuery();
};
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  doQuery();
};
const doQuery = async () => {
  console.log(pagination.value);
  const request = {
    ...pagination.value,
    ...queryForm.value
  };
  loading.value = true;
  await getCategoryList(request).then((res) => {
    tableData.value = res.data?.record;
    totalArticleCount.value = res.data?.total;
    const timer = setTimeout(() => {
      loading.value = false;
      clearTimeout(timer);
    }, 500);
  }).catch((err) => {
    console.log(err);
    loading.value = false;
  });
};

const queryForm = ref({
  name: ''
});
const reset = () => {
  queryForm.value = {
    name: ''
  };
  doQuery();
};

onMounted(async () => {
  console.log('文章分类')
  await doQuery();
});

const formData = ref({
  id: undefined,
  name: '',
  remark: ''
});
const openDialog = async (type, row) => {
  dialog.value.visible = true;
  dialog.value.title = type === 'add' ? '新增分类' : '编辑分类';
  resetFormData();
  if (type === 'edit') {
    console.log('编辑分类');
    await nextTick(() => {
      formData.value = {
        id: row.id,
        name: row.name,
        remark: row.remark
      };
    });
  }
};
const resetFormData = () => {
  formData.value = {
    id: undefined,
    name: '',
    remark: ''
  };
};
const close = () => {
  resetFormData();
  dialog.value.visible = false;
};
const confirm = async () => {
  await saveCategory(formData.value).then(res => {
    console.log(res);
    ElMessage.success('保存成功');
    close();
    doQuery();
  }).catch(err => {
    console.log(err);
  })
};
</script>

<template>
  <div class="v-container">
    <div class="v-query">
      <el-input v-model="queryForm.name" placeholder="请输入分类名称" clearable
                style="width: 200px;margin-right: 10px"/>
      <el-button type="primary" size="small" @click="doQuery">查询</el-button>
      <el-button type="info" size="small" @click="reset">重置</el-button>
      <el-button type="success" size="small" @click="openDialog('add', undefined)">新增</el-button>
    </div>
    <div class="v-category-table">
      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="name" label="分类名称" width="180"/>
        <el-table-column prop="articleNum" label="关联文章" width="100"/>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column prop="createdTime" label="创建时间" width="180"/>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除该分类吗？" placement="top" @confirm="deleteCategory(scope.row)">
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty :image-size="200" description="还没有分类哦..."/>
        </template>
      </el-table>
      
      <el-pagination v-if="totalArticleCount > 0" size="small" background
                     layout="prev, pager, next, sizes"
                     :total="totalArticleCount"
                     :page-sizes="[5, 10, 20, 50, 100]"
                     v-model:current-page="pagination.pageNum"
                     v-model:page-size="pagination.pageSize"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     class="v-page"/>
    </div>
  </div>
  
  
  <!-- 新增、编辑 -->
  <el-dialog v-model="dialog.visible" :title="dialog.title" @close="close" width="500" center draggable>
    <el-form :model="formData" label-position="top" label-width="auto" style="max-width: 600px">
      <el-form-item label="分类名称">
        <el-input v-model="formData.name" maxlength="50" show-word-limit/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.remark" type="textarea" :rows="4" maxlength="255" show-word-limit/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 重写 element plus 样式 */
:deep(.el-textarea__inner) {
  resize: none;
}

.v-category-table {
  background-color: #fff;
  padding-bottom: 6px;
}
</style>